package gui.action;

import generated.domain.world.World;
import gui.Activator;
import gui.editor.WorldMapEditor;
import gui.editor.WorldMapEditorInput;

import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.SelectionProviderAction;

public class OpenWorldMapEditorAction extends SelectionProviderAction {

    public OpenWorldMapEditorAction(final ISelectionProvider provider,
            final String text) {
        super(provider, text);
    }

    public void run() {
        IStructuredSelection structuredSelection = getStructuredSelection();
        Object firstElement = structuredSelection.getFirstElement();
        openEditor(firstElement);
    }

    public static boolean openEditor(final Object world) {
        boolean result = false;
        IWorkbench workbench = PlatformUI.getWorkbench();
        IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
        IWorkbenchPage activePage = window.getActivePage();

        IEditorInput input = new WorldMapEditorInput((World)world);
		if (input != null) {
			try {
				activePage.openEditor(input, WorldMapEditor.ID, true);
				result = true;
			} catch (final PartInitException pie) {
				Shell shell = window.getShell();
				String title = "Error";
				ErrorDialog.openError(shell, title, pie.getMessage(), pie
						.getStatus());
				Activator.getDefault().getLog().log(pie.getStatus());
			}
		}
        return result;
    }
}